//
//  ThumbButton.m
//  Four_Fit_New
//
//  Created by lanou on 16/7/20.
//  Copyright © 2016年 xmaz. All rights reserved.
//

#import "ThumbButton.h"
#import "EmitterView.h"

#define dispatch_main_sync_safe(block)\
if ([NSThread isMainThread]) {\
block();\
} else {\
dispatch_sync(dispatch_get_main_queue(), block);\
}

#define dispatch_main_async_safe(block)\
if ([NSThread isMainThread]) {\
block();\
} else {\
dispatch_async(dispatch_get_main_queue(), block);\
}

#define kThumbButtonHasFailWithThumb @"kThumbButtonHasFailWithThumb"
const double startDuration = 0.5f;
const double endDuration = 0.4f;

@interface ThumbButton ()

{
    BOOL _selected;
}
@property (nonatomic, strong) EmitterView *emiView;
@end

@implementation ThumbButton

- (instancetype)init
{
    CGRect frame = CGRectMake(0, 0, 30, 30);
    self = [self initWithFrame:frame];
    [self setupSubViews];
    return self;
}

- (void)setupSubViews
{
    _selected = NO;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(thumbButtonFailed) name:kThumbButtonHasFailWithThumb object:nil];
    
    if (_selected) {
        [self setImage:[UIImage imageNamed:@"Like-Blue"] forState:UIControlStateNormal];
    }else {
        [self setImage:[UIImage imageNamed:@"Like-PlaceHold"] forState:UIControlStateNormal];
    }
    [self addTarget:self action:@selector(emiButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [self insertSubview:self.emiView atIndex:0];
}

- (EmitterView *)emiView
{
    if (!_emiView) {
        _emiView = [[EmitterView alloc] initWithFrame:self.bounds];
    }
    return _emiView;
}

- (void)setHighlighted:(BOOL)highlighted
{
    // 重写点击高亮效果，这样动画看起来更流畅
}

#pragma mark - 点击事件
- (void)emiButtonClick
{
    if (_selected) {
        [self hideThumbAnimation];
    }else {
        [self startThumbAnimation];
        [self.emiView animate];
    }
    
    if (self.buttonClick) {
        self.buttonClick();
    }
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(thumbButtonClick)]) {
        [self.delegate thumbButtonClick];
    }
}

#pragma mark - 点赞动画
- (void)startThumbAnimation
{
    __weak typeof(self) weakSelf = self;
    self.transform = CGAffineTransformIdentity;
    
    // 这里用了个偷巧方法，让按钮在最大的时候设置为按下的图片
    dispatch_time_t delay = dispatch_time(DISPATCH_TIME_NOW, startDuration/3.f * NSEC_PER_SEC);
    dispatch_after(delay, dispatch_get_main_queue(), ^{
        [self setImage:[UIImage imageNamed:@"Like-Blue"] forState:UIControlStateNormal];
    });
    
    [UIView animateKeyframesWithDuration:startDuration delay:0 options:0 animations:^{
        
        // 设置控件图片为选中后图片，然后让控件放大1.5倍
        [weakSelf setImage:[UIImage imageNamed:@"Like-Blue"] forState:UIControlStateNormal];
        [UIView addKeyframeWithRelativeStartTime:0 relativeDuration:1/3.0 animations:^{
            typeof(weakSelf) strongSelf = weakSelf;
            dispatch_main_sync_safe(^{
                strongSelf.transform = CGAffineTransformMakeScale(1.5f, 1.5f);
            });
        }];
        
        // 再让控件缩小到原来的0.8倍
        [UIView addKeyframeWithRelativeStartTime:1/3.0 relativeDuration:1/3.0 animations:^{
            typeof(weakSelf) strongSelf = weakSelf;
            dispatch_main_sync_safe(^{
                strongSelf.transform = CGAffineTransformMakeScale(0.8f, 0.8f);
            });
        }];
        
        // 最后让控件回到原来大小
        [UIView addKeyframeWithRelativeStartTime:2/3.0 relativeDuration:1/3.0 animations:^{
            typeof(weakSelf) strongSelf = weakSelf;
            dispatch_main_sync_safe(^{
                strongSelf.transform = CGAffineTransformMakeScale(1.0, 1.0);
            });
        }];
    } completion:^(BOOL finished) {
        _selected = YES;
    }];
}

#pragma mark - 取消点赞动画
- (void)hideThumbAnimation
{
    __weak typeof(self) weakSelf = self;
    self.transform = CGAffineTransformIdentity;
    
    dispatch_time_t delay = dispatch_time(DISPATCH_TIME_NOW, endDuration/2.f * NSEC_PER_SEC);
    dispatch_after(delay, dispatch_get_main_queue(), ^{
        [self setImage:[UIImage imageNamed:@"Like-PlaceHold"] forState:UIControlStateNormal];
    });
    
    [UIView animateKeyframesWithDuration:endDuration delay:0 options:0 animations:^{
        // 先让控件缩小一点
        [weakSelf setImage:[UIImage imageNamed:@"Like-PlaceHold"] forState:UIControlStateNormal];
        [UIView addKeyframeWithRelativeStartTime:0 relativeDuration:1/2.0 animations:^{
            typeof(weakSelf) strongSelf = weakSelf;
            dispatch_main_sync_safe(^{
                strongSelf.transform = CGAffineTransformMakeScale(0.8, 0.8);
            });
        }];
        // 再让控件回到正常大小
        [UIView addKeyframeWithRelativeStartTime:1/2.0 relativeDuration:1/2.0 animations:^{
            typeof(weakSelf) strongSelf = weakSelf;
            dispatch_main_sync_safe(^{
                strongSelf.transform = CGAffineTransformMakeScale(1.0, 1.0);
            });
        }];
    } completion:^(BOOL finished) {
        _selected = NO;
    }];
}

#pragma mark - 点赞失败
- (void)thumbButtonFailed
{
    if (_selected == NO) return;
    [self setImage:[UIImage imageNamed:@"Like-PlaceHold"] forState:UIControlStateNormal];
    _selected = NO;
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:kThumbButtonHasFailWithThumb object:nil];
}

@end
